<template>
  <div class="app-container">
    <div class="filter-container">
      <org-unit-select v-model="filters.orgUnitId" :org-unit-type="1" placeholder="请选择店铺" />
      <el-input v-model="filters.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="filters.author" placeholder="作者" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="filters.tag" placeholder="标签" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      玩家数量
      <el-input-number v-model="filters.minPlayers" :min="1" :max="99" style="width: 120px;" controls-position="right" class="filter-item" @keyup.enter.native="handleFilter" />
      - <el-input-number v-model="filters.maxPlayers" :min="filters.minPlayers" :max="99" style="width: 120px;" controls-position="right" class="filter-item" @keyup.enter.native="handleFilter" />
      &nbsp;&nbsp;时长
      <el-input-number v-model="filters.minDuration" :min="1" controls-position="right" :max="99" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />
      - <el-input-number v-model="filters.maxDuration" :min="filters.minDuration" controls-position="right" :max="99" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />小时
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-if="canAddShopMovie" v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleAdd">添加剧本</el-button>
      <div style="margin-left: 3.125rem;">
        <el-checkbox v-for="col in dynamicColumn.shopMovies" v-model="col.show" class="filter-item" style="margin-left:10px;" @change="tableKey=tableKey+1">
          {{ col.name }}
        </el-checkbox>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column prop="movieName" label="名称" min-width="160" sortable />
      <el-table-column prop="author" label="作者" width="110" sortable />
      <el-table-column prop="movieVersion" label="版本" width="100" sortable />
      <el-table-column v-if="checkColumn('tag')" prop="tag" label="标签" min-width="160" :formatter="formatTag" />
      <el-table-column v-if="checkColumn('duration')" prop="duration" label="时长(小时)" width="90" />
      <el-table-column label="玩家数量" width="100" :formatter="formatPlayers" />
      <el-table-column v-if="checkColumn('playTimes')" prop="playTimes" label="开本次数" width="110" sortable />
      <el-table-column prop="price" label="价格(元)" width="80" :formatter="formatPrice" />
      <el-table-column prop="status" label="状态" width="70" :formatter="formatStatus" />
      <el-table-column v-if="checkColumn('movieLevelName')" prop="movieLevelName" label="类别" width="90" />
      <el-table-column prop="orgUnitName" label="所属店铺" min-width="100" />
      <el-table-column v-if="checkColumn('operation')" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === 1" size="small" @click="online(scope.index, scope.row)">上线</el-button>
          <el-button v-if="scope.row.status === 0" size="small" @click="offline(scope.index, scope.row)">下线</el-button>
          <el-button size="small" @click="handleEdit(scope.index, scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <!--添加剧本-->
    <el-dialog title="添加剧本" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="onAddDialogClose">
      <el-container>
        <el-aside width="200px">
          <el-image fit="contain" :src="addForm.coverUrl">
            <div slot="error" class="image-slot">
            </div>
          </el-image>
        </el-aside>
        <el-main>
          <el-row>
            <el-col :span="24"><movie-select ref="addMovieSelector" v-model="addForm.movieId" :disabled="editId!==0" style="width: 90%;" /></el-col>
          </el-row>
          <el-row>
            <el-col :span="6">剧本版本：{{ movieItem.version }}</el-col>
            <el-col :span="6">剧本作者：{{ movieItem.author }}</el-col>
            <el-col :span="12">剧本标签：{{ movieItem.tag }}</el-col>
          </el-row>
          <el-row>
            <el-col :span="6">玩家数量：{{ movieItem.minPlayers }}-{{ movieItem.maxPlayers }}人</el-col>
            <el-col :span="6">预估时长：{{ movieItem.duration }}小时</el-col>
            <el-col :span="6">开本次数：{{ movieItem.playTimes }}</el-col>
            <el-col :span="6">剧本类别：{{ movieItem.movieLevelName }}</el-col>
          </el-row>
          <el-row>
            <el-col v-for="(item) in addForm.roles" :key="item.id" :span="6">
              <el-card class="box-card" :body-style="{ padding: '0px' }">
                <el-image :src="item.fileUrl">
                  <div slot="error" class="image-slot">
                  </div>
                </el-image>
                <div style="padding: 14px;text-align: center">
                  <div>{{ item.name }}</div>
                  <span>{{ item.description }}</span>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="addFormLoading" @click="addSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination'
import MovieSelect from '@/views/components/movie-select'
import { downloadMovieCover, movieDetails } from '@/api/movie'
import { listShopMovie, saveShopMovie, offline, online, modifyShopMovie } from '@/api/shop-movie'
import util from '@/utils/util'
import { downloadMovieRoleFile, downloadMultiMovieRoleFile, listMovieRoles } from '@/api/play-roles'
import OrgUnitSelect from '@/views/components/org-unit-select'

export default {
  name: 'ShopMovie',
  components: { OrgUnitSelect, Pagination, MovieSelect },
  directives: { waves },
  data() {
    return {
      logo: 'ic_launcher.png',
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        name: '',
        author: null,
        tag: null,
        minPlayers: 0,
        maxPlayers: 0,
        minDuration: 0,
        maxDuration: 0,
        orgUnitId: null
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },
      editId: 0,
      addFormVisible: false,
      addFormLoading: false,
      addForm: {
        movieId: null,
        movieVersion: '',
        coverUrl: '',
        roles: []
      },
      movieItem: {
        version: '',
        author: '',
        tag: [],
        movieLevelName: '',
        minPlayers: null,
        maxPlayers: null,
        duration: null,
        playTimes: null
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'formLabelWidth', 'dynamicColumn']),
    canAddShopMovie() {
      const roles = this.userInfo.roles || []
      if (this.userInfo.orgUnitType === 2 && roles.indexOf('Manager') !== -1) {
        return true
      }
      return roles.indexOf('ShopManager') !== -1
    }
  },
  watch: {
    'addForm.movieId': {
      handler() {
        this.refreshMovieInfo()
      }
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
  },
  methods: {
    refreshMovieInfo() {
      if (this.$refs.addMovieSelector) {
        this.loadMovieInfo()
      } else {
        console.log('$refs.addMovieSelector is false')
        this.$nextTick(() => {
          this.refreshMovieInfo()
        })
      }
    },
    checkColumn(col) {
      if (this.dynamicColumn.shopMovies.hasOwnProperty(col)) {
        return this.dynamicColumn.shopMovies[col].show
      }
      return true
    },
    formatTag(row) {
      if (row.tag && Array.isArray(row.tag)) {
        return row.tag.join(' ')
      }
    },
    formatPlayers(row) {
      if (row.minPlayers && row.maxPlayers) {
        return row.minPlayers + '-' + row.maxPlayers + '人'
      } else if (row.minPlayers) {
        return '至少' + row.minPlayers + '人'
      } else if (row.maxPlayers) {
        return '最多' + row.maxPlayers + '人'
      } else {
        return ''
      }
    },
    formatPrice(row) {
      return util.currency.format(row.price)
    },
    formatStatus(row) {
      const st = parseInt(row.status)
      if (st === 0) {
        return '已上线'
      } else if (st === 1) {
        return '已下线'
      }
      return ''
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      listShopMovie(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    handleAdd() {
      this.addFormVisible = true
      this.resetAddForm()
    },
    addSubmit() {
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        this.addFormLoading = true
        const param = {
          movieId: this.addForm.movieId,
          movieVersion: this.addForm.movieVersion
        }
        if (this.editId) {
          this.modifySubmit(param)
        } else {
          this.saveSubmit(param)
        }
      })
    },
    saveSubmit(param) {
      saveShopMovie(param).then(({ success, message }) => {
        this.addFormLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '提交失败',
            type: 'error'
          })
        }
      }, () => {
        this.addFormLoading = false
      })
    },
    handleEdit(index, row) {
      this.addFormVisible = true
      this.editId = row.id
      this.addForm.movieVersion = row.movieVersion
      this.addForm.movieId = row.movieId
    },
    modifySubmit(param) {
      modifyShopMovie(this.editId, param).then(({ success, message }) => {
        this.addFormLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '提交失败',
            type: 'error'
          })
        }
      }, () => {
        this.addFormLoading = false
      })
    },
    onAddDialogClose() {
      this.resetAddForm()
    },
    resetAddForm() {
      this.editId = 0
      this.addForm = {
        movieId: null,
        movieVersion: '',
        coverUrl: '',
        roles: []
      }
      this.movieItem = {
        version: '',
        author: '',
        tag: [],
        movieLevelName: '',
        minPlayers: null,
        maxPlayers: null,
        duration: null,
        playTimes: null
      }
    },
    loadMovieInfo() {
      if (!this.addForm.movieId) {
        // 没有剧本id,查不了数据
        console.log('addForm.movieId=' + this.addForm.movieId)
        return
      }
      const movieItem = this.$refs.addMovieSelector.movieItem(this.addForm.movieId)
      if (movieItem) {
        this.movieItem = movieItem
        this.showMovie()
      } else {
        // 修改的情况，movieSelector没有加载列表数据,所以拿不到数据
        movieDetails(this.addForm.movieId, this.addForm.movieVersion).then(({ success, message, data }) => {
          if (success) {
            this.movieItem = data
            this.showMovie()
          } else {
            this.$message({
              message: message || '查询剧本失败',
              type: 'error'
            })
          }
        }, () => {
        })
      }
    },
    showMovie() {
      if (!this.editId) {
        this.addForm.movieVersion = this.movieItem.version
      }
      downloadMovieCover(this.movieItem.id, this.movieItem.version).then(res => {
        const blob = new Blob([res.data])
        this.addForm.coverUrl = (window.URL || window.webkitURL).createObjectURL(blob)
      }, (res) => {
        this.addForm.coverUrl = this.logo
      })
      listMovieRoles(this.movieItem.id, this.movieItem.version).then(({ success, data }) => {
        if (success && data) {
          const arr = []
          for (let i = 0; i < data.length; ++i) {
            const item = data[i]
            item.description = item.gender + '|' + item.crossGender + '反串'
            arr.push(new Promise((resolve, reject) => {
              downloadMovieRoleFile(this.movieItem.id, this.movieItem.version, item.id).then(res => {
                const blob = new Blob([res.data])
                item.fileUrl = (window.URL || window.webkitURL).createObjectURL(blob)
                resolve(item)
              }, (res) => {
                item.fileUrl = this.logo
                resolve(item)
              })
            }))
          }
          downloadMultiMovieRoleFile(arr).then(res => {
            this.addForm.roles = res
          })
        } else {
          this.addForm.roles = []
        }
      }, res => {
        this.addForm.roles = []
      })
    },
    online(index, row) {
      this.$confirm('确认上线吗？', '提示', {}).then(() => {
        this.listLoading = true
        online(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.loadPageList()
          } else {
            this.$message({
              message: message || '操作失败',
              type: 'error'
            })
          }
        }, () => {
          this.listLoading = false
        })
      })
    },
    offline(index, row) {
      this.$confirm('确认下线吗？', '提示', {}).then(() => {
        this.listLoading = true
        offline(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.loadPageList()
          } else {
            this.$message({
              message: message || '操作失败',
              type: 'error'
            })
          }
        }, () => {
          this.listLoading = false
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.image-slot {
  width: 100px;
  height: 100px;
}
.el-row {
  margin-bottom: 10px;
  &:last-child {
     margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.box-card {
  border: 1px solid transparent;
  border-radius: 15px;
  background-color: rgba(255,255,255,0.1);
  box-shadow: 5px 5px 0 0 rgba(0,0,0,0.2);
}
</style>
